package com.ywb.edugui.controller;

import com.alibaba.druid.util.StringUtils;
import com.ywb.edugui.dao.UserDao;
import com.ywb.edugui.dao.facotry.DaoFactory;
import com.ywb.edugui.entity.User;
import com.ywb.edugui.utils.MyJDialog;
import com.ywb.edugui.view.user.LoginView;
import com.ywb.edugui.view.MainView;
import com.ywb.edugui.view.user.RegistrationView;

import javax.swing.*;
import java.awt.*;
import java.util.Map;

/**
 * @Author ywb
 */
public class UserController {
    private UserDao userDao = DaoFactory.getUserDao();
    private Container userView;

    public UserController(Container view){
        userView = view;
    }

    public void login(String username, String password) {
        LoginView loginView = (LoginView) userView;
        Map<String, String> result = userDao.login(username, password);
        if( result.get("msg") != null){
            JOptionPane.showMessageDialog(loginView, result.get("msg"), "LoginView", JOptionPane.WARNING_MESSAGE);
            loginView.getTfPassword().setText("");
            loginView.getTfPassword().grabFocus();
            return;
        }
        new MyJDialog(loginView, "登陆成功");
//        JOptionPane.showMessageDialog(loginView, "登录成功! 正在进入主页面...", "LoginView", JOptionPane.INFORMATION_MESSAGE);
        loginView.dispose();
        new MainView().setVisible(true);
    }
    public void Register(String username, String password, String rePassword, String code){
        RegistrationView view = (RegistrationView) userView;
        //        1. 验证完整性
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(rePassword) || StringUtils.isEmpty(code)){
            JOptionPane.showMessageDialog(view, "请输入完整信息");
            return;
        }
//        2. 验证图片验证码
        if(!view.getCodeConfirm().equalsIgnoreCase(code)) {
            JOptionPane.showMessageDialog(view, "请输入正确的验证码");
//            重置验证码
            view.initCode();
//            获得焦点
            view.getTfCode().grabFocus();
            return;
        }
//        3. 验证重复密码
        if(!password.equals(rePassword)) {
            JOptionPane.showMessageDialog(view, "两次密码不一致");
            view.resetTextField(view.getTfPassword(), view.getTfRePassword());
            view.getTfPassword().grabFocus();
            return;
        }
//        4. 验证用户名是否存在
        if(userDao.getByUsername(username) != null){
            JOptionPane.showMessageDialog(view, "已存在该用户名,请重新输入");
            view.resetTextField();
            return;
        }

        userDao.add(new User().setUsername(username).setPassword(password));
        JOptionPane.showMessageDialog(view,"添加成功!自动登录...");
        view.dispose();
        new MainView().setVisible(true);
    }
}
